package com.shenmazong.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shenmazong.mapper.TbCompanyJobMapper;
import com.shenmazong.mapper.TbCompanyMapper;
import com.shenmazong.vo.CompanyJobVo;
import com.shenmazong.vo.CompanyVo;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * @author 阿瑞
 * @version 1.0
 * @description TODO
 * @class MqReceive ???
 * @date 2021/9/25 14:53
 */
@Component
public class CompanyReceive {
    @Autowired
    private TbCompanyMapper tbCompanyMapper;
    @Autowired
    private TbCompanyJobMapper tbCompanyJobMapper;
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @RabbitListener(queues =MqConfig.COMPANY_QUEUE )
    public void receiveCompany(String msg)  {
        ObjectMapper objectMapper = new ObjectMapper();
        HashMap<String, String> map = null;
        try {
            map = objectMapper.readValue(msg, HashMap.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        if (map.get("saveCompany")!=null){
            String o = map.get("saveCompany");
            try {
                CompanyVo companyVo = objectMapper.readValue(o, CompanyVo.class);
                List<CompanyJobVo> job = tbCompanyJobMapper.findAllJob(companyVo.getCompanyId());
                companyVo.setList(job);
                elasticsearchRestTemplate.save(companyVo);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }else {
            String id= map.get("delCompany");
            CompanyVo one = tbCompanyMapper.getOne(Long.parseLong(id));
            List<CompanyJobVo> job = tbCompanyJobMapper.findAllJob(one.getCompanyId());
            one.setList(job);
            elasticsearchRestTemplate.save(one);
        }
    }
}
